-- IPTU

BEGIN TRANSACTION

DECLARE @TLA_COD INT, @DIV_COD INT, @LAN_VALOR_ORIGINAL MONEY
DECLARE @LANCAMENTOS CURSOR
SET @LANCAMENTOS = CURSOR 
	FOR SELECT TLA_COD FROM TRB_IPTU A
		WHERE EXE_ANO = 2007
		AND NOT EXISTS ( SELECT 1 FROM TRB_LANCAMENTO B JOIN TRB_BAIXA C ON C.LAN_COD = B.LAN_COD WHERE B.TLA_COD = A.TLA_COD AND LAN_PARCELA = 0 AND LAN_SITUACAO = 'N' )
		AND ( SELECT COUNT(*) FROM TRB_LANCAMENTO B WHERE B.TLA_COD = A.TLA_COD AND LAN_PARCELA > 0 AND LAN_SITUACAO = 'N' AND NOT EXISTS ( SELECT 1 FROM TRB_BAIXA C WHERE C.LAN_COD = B.LAN_COD ) ) = 10
OPEN @LANCAMENTOS 
FETCH NEXT FROM @LANCAMENTOS INTO @TLA_COD
WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT @DIV_COD = DIV_COD, @LAN_VALOR_ORIGINAL = LAN_VALOR_ORIGINAL 
		FROM TRB_DIVIDA_LANCAMENTO A JOIN TRB_LANCAMENTO B ON B.LAN_COD = A.LAN_COD 
		WHERE TLA_COD = @TLA_COD AND B.LAN_PARCELA = 0
	
	IF @DIV_COD IS NOT NULL 
	BEGIN
		UPDATE TRB_DIVIDA SET DIV_VALOR_ORIGINAL = @LAN_VALOR_ORIGINAL WHERE DIV_COD = @DIV_COD
	END
	FETCH NEXT FROM @LANCAMENTOS INTO @TLA_COD
END
CLOSE @LANCAMENTOS 
DEALLOCATE @LANCAMENTOS 

rollback